//
//  MCConsumeViewItemTwoController.m
//  ERP
//
//  Created by QA on 15/12/11.
//  Copyright © 2015年 ShangHai HaoLei Software Technology Co., Ltd. All rights reserved.
//

#import "MCConsumeViewItemTwoController.h"

#import "WebServiceCommonRequest.h"
#import "UITableView+Custom.h"
#import "NSDictionary+DataFormat.h"

#import "GEObjectValueTableViewCell.h"
#import "GEProgressBarTableViewCell.h"
#import "AutoTextTableViewCell.h"
#import "MCConsumeTwoViewCell.h"
#import "DateTimeFormat.h"
#import "GEObjectButton.h"

#import "MJRefresh.h"
#import "GEDateFromatter.h"
#import "MCConsumeDetailViewController.h"

@interface MCConsumeViewItemTwoController ()

@property (nonatomic, strong) UINavigationController *navigationController;

@property (strong, nonatomic) NSMutableArray *resultData;

@property (strong, nonatomic) NSString *searchStartTime;
@property (strong, nonatomic) NSString *searchEndTime;

@end

@implementation MCConsumeViewItemTwoController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [self setTitle: @"原材消耗_工程消耗"];
    }
    return self;
}

- (instancetype)initWithNavigationController:(UINavigationController*)navigationController
{
    self = [super init];
    if (self) {
        self.navigationController = navigationController;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.resultData = [NSMutableArray array];
    self.tableView.tableFooterView= [[UIView alloc] init];
    
    //设置默认搜索时间(本月)
    NSString *time = [GEDateFromatter formmatTimeDate:[NSDate date] format:@"yyyy-MM"];
    self.searchStartTime = [NSString stringWithFormat:@"%@-01",time];
    self.searchEndTime = [GEDateFromatter formmatTimeDate:[NSDate date]];
    
    [self setupRefresh];
}

- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    [self.tableView headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
}

- (void)stopRefresh
{
    //移除下拉加载数据
    [self.tableView headerEndRefreshing];
    [self.tableView footerEndRefreshing];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)updateTableStartTime:(NSString*)startTime endTime:(NSString*)endTime
{
    self.searchStartTime = startTime;
    self.searchEndTime = endTime;
    
    [self.resultData removeAllObjects];
    [self.tableView reloadData];
    [self.tableView headerBeginRefreshing];
}

#pragma mark 开始进入刷新状态

- (void)headerRereshing
{
    NSNumber *stateNumber = [NSNumber numberWithInteger:0];
    NSNumber *endNumber = [NSNumber numberWithInteger:20];
    [self getNetWorkDataIsReresh:YES state:stateNumber end:endNumber];
}

- (void)footerRereshing
{
    NSNumber *stateNumber = [NSNumber numberWithInteger:self.resultData.count + 1];
    NSNumber *endNumber = [NSNumber numberWithInteger:self.resultData.count + 20];
    [self getNetWorkDataIsReresh:NO state:stateNumber end:endNumber];
}

#pragma mark 网络获取数据

- (void)getNetWorkDataIsReresh:(BOOL)isReresh state:(NSNumber*)state end:(NSNumber*)end
{
    //组装条件：1、日期；2、开始行；3、结束行；4、状态
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setInterfaceType:InterfaceTypeERP];
    [content setModuleType:@"YCL_DYXH_GCMC_LIST20160219"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    
    //设置站点ID
    StationInfoEntity *model = [[GetUserStationService sharedService] getSelectStationEntity];
    [content setStationID:[model.stationId integerValue]];
    
    [content addParameterKey:@"起始条数" value:state];
    [content addParameterKey:@"结束条数" value:end];
    [content addParameterKey:@"开始日期" value:self.searchStartTime];
    [content addParameterKey:@"截止日期" value:self.searchEndTime];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        if(isReresh) [self.tableView headerEndRefreshing];
        else [self.tableView footerEndRefreshing];
        //添加数据，刷新页面
        NSArray *firstArray = nil;
        if(result.resultArray && result.resultArray.count>0)
            firstArray = [result.resultArray firstObject];
        
        if(firstArray && firstArray.count>0){
            if(isReresh) [self.resultData removeAllObjects];
            [self.resultData addObjectsFromArray:firstArray];
            [self.tableView setTableViewNotDataDrawText:nil isShow:NO];
            [self.tableView reloadData];
        } else if(isReresh){
            [self.tableView setTableViewNotDataDrawText:@"暂无数据" isShow:YES];
        }
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        if(isReresh)[self errorInfoViewText:@"哦，出错了"];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        if(isReresh)[self errorInfoViewText:@"无法连接网络"];
    }];
}
- (void)errorInfoViewText:(NSString*)label
{
    [self.tableView headerEndRefreshing];
    [self.tableView footerEndRefreshing];
    
    if (self.tableView.visibleCells.count <= 0) {
        [self.tableView setTableViewNotDataDrawText:label isShow:YES];
    } else {
        [self.tableView setTableViewNotDataDrawText:nil isShow:NO];
        [self showErrorHUDText:label];
    }
}

#pragma mark
#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.resultData.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *identifier = [NSString stringWithFormat:@"MCConsumeTwoViewCell"];
    MCConsumeTwoViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[MCConsumeTwoViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    
    NSDictionary *mDictionary = [self.resultData objectAtIndex:indexPath.row];
    cell.titleLabel.text = [mDictionary objectFormatStringForKey:@"工程名称" defaults:@"未知"];
    cell.fhflLabel.text = [mDictionary objectFormatFloatStringForKey:@"发货量" retain:1 except:10000 exceptFormat:@"发货%@万方" format:@"发货%@方"];
    cell.scflLabel.text = [mDictionary objectFormatFloatStringForKey:@"生产量" retain:1 except:10000 exceptFormat:@"生产%@万方" format:@"生产%@方"];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 52;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary *mDictionary = [self.resultData objectAtIndex:indexPath.row];
    NSArray *values = @[self.searchStartTime, self.searchEndTime, mDictionary];
    
    MCConsumeDetailViewController *view = [[MCConsumeDetailViewController alloc] initWithValue:values];
    [self.navigationController pushViewController:view animated:YES];

}

@end
